// 记录要删除房屋的id和索引
let houseId = ''
let houseIndex = 0
Page({
  data: {
    dialogVisible: false,
    houseList: [],
    isEmpty: false,
  },
  onShow() {
    this.getHouseList()
  },
  // 1. 获取房屋列表
  async getHouseList() {
    // 请求数据接口
    const { code, data: houseList } = await wx.http.get('/room')
    // 检测接口返回的结果
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败~')
    // 渲染数据
    this.setData({ houseList, isEmpty: houseList.length === 0 })
  },
  swipeClose(ev) {
    const { position, instance } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })
      // 待删除的房屋id和索引
      houseId = ev.mark.id
      houseIndex = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  // 3. 关闭提示对话框
  dialogClose(ev) {
    ev.detail === 'confirm' && this.deleteHouse()
  },
  // 4. 删除房屋
  async deleteHouse() {
    console.log('调用删除接口')
    const { code } = await wx.http.delete('/room/' + houseId)
    console.log(code)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')

    // 4.2 更新列表
    const { houseList } = this.data
    houseList.splice(houseIndex, 1)
    this.setData({
      houseList,
      isEmpty: houseList.length === 0,
    })
  },

  goDetail(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
